package com.adjaisd.scarecrow.common.utils.influx;

import com.adjaisd.scarecrow.common.config.InfluxConfig;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class InfluxClient {

    @Autowired
    InfluxConfig influxConfig;

    @Bean
    public InfluxDB influxDB() {
        InfluxDB influxDB = InfluxDBFactory.connect(influxConfig.getUrl(), influxConfig.getUser(), influxConfig.getPassword());
        try {
            /**
             * 异步插入： enableBatch这里第一个是point的个数，第二个是时间，单位毫秒 point的个数和时间是联合使用的，如果满100条或者2000毫秒
             * 满足任何一个条件就会发送一次写的请求。
             */
            influxDB.setDatabase(influxConfig.getDatabase())
                    .enableBatch(100, 2000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            influxDB.setRetentionPolicy("autogen");
        }
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }

}
